class Gomoku {
    constructor() {
        this.boardSize = 15;
        this.board = Array(this.boardSize).fill().map(() => Array(this.boardSize).fill(null));
        this.currentPlayer = 'black';
        this.gameOver = false;
        this.scores = {
            black: 0,
            white: 0
        };
        this.winningPieces = [];
        this.isAIMode = false;
        this.aiDifficulty = 'medium';
        this.isAIThinking = false;
        this.boardElement = document.getElementById('board');
        
        this.init();
    }

    init() {
        this.createBoard();
        this.bindEvents();
        this.updateStatus();
        this.updateScores();
    }

    createBoard() {
        if (!this.boardElement) return;
        this.boardElement.innerHTML = '';

        const gridContainer = document.createElement('div');
        gridContainer.style.display = 'grid';
        gridContainer.style.gridTemplateColumns = `repeat(${this.boardSize}, 44px)`;
        gridContainer.style.gap = '0';
        gridContainer.style.position = 'relative';

        for (let i = 0; i < this.boardSize; i++) {
            for (let j = 0; j < this.boardSize; j++) {
                const cell = document.createElement('div');
                cell.className = 'cell';
                cell.dataset.row = i;
                cell.dataset.col = j;

                if (i === 0) cell.style.borderTop = '2px solid rgba(0, 0, 0, 0.8)';
                if (i === this.boardSize - 1) cell.style.borderBottom = '2px solid rgba(0, 0, 0, 0.8)';
                if (j === 0) cell.style.borderLeft = '2px solid rgba(0, 0, 0, 0.8)';
                if (j === this.boardSize - 1) cell.style.borderRight = '2px solid rgba(0, 0, 0, 0.8)';

                gridContainer.appendChild(cell);
            }
        }

        this.boardElement.appendChild(gridContainer);
    }

    bindEvents() {
        if (!this.boardElement) return;
        
        this.boardElement.addEventListener('click', (e) => {
            if (this.gameOver || this.isAIThinking) return;
            if (this.isAIMode && this.currentPlayer === 'white') return;

            const cell = e.target.closest('.cell');
            if (!cell) return;

            const row = parseInt(cell.dataset.row);
            const col = parseInt(cell.dataset.col);

            if (this.isValidMove(row, col)) {
                this.makeMove(row, col);
            }
        });

        const restartButton = document.getElementById('restart');
        if (restartButton) {
            restartButton.addEventListener('click', () => this.restart());
        }

        const playAgainButton = document.querySelector('.play-again');
        if (playAgainButton) {
            playAgainButton.addEventListener('click', () => {
                this.hideModal();
                this.restart();
            });
        }

        const modeToggle = document.getElementById('mode-toggle');
        if (modeToggle) {
            modeToggle.addEventListener('click', () => {
                this.isAIMode = !this.isAIMode;
                modeToggle.textContent = this.isAIMode ? '切换为双人对战' : '切换为人机对战';
                const aiSettings = document.getElementById('ai-settings');
                if (aiSettings) {
                    aiSettings.style.display = this.isAIMode ? 'flex' : 'none';
                }
                const whitePlayerName = document.getElementById('white-player-name');
                if (whitePlayerName) {
                    whitePlayerName.textContent = this.isAIMode ? 'AI得分' : '白方得分';
                }
                this.restart();
            });
        }

        const difficultySelect = document.getElementById('ai-difficulty');
        if (difficultySelect) {
            difficultySelect.addEventListener('change', (e) => {
                this.aiDifficulty = e.target.value;
            });
        }
    }

    async makeMove(row, col) {
        this.board[row][col] = this.currentPlayer;
        
        const cell = document.querySelector(`[data-row="${row}"][data-col="${col}"]`);
        const piece = document.createElement('div');
        piece.className = `piece ${this.currentPlayer}`;
        cell.appendChild(piece);

        setTimeout(() => {
            piece.classList.add('show');
        }, 50);

        if (this.checkWin(row, col)) {
            this.gameOver = true;
            this.scores[this.currentPlayer]++;
            this.updateScores();
            this.highlightWinningPieces();
            setTimeout(() => this.showWinner(), 500);
            return;
        }

        this.currentPlayer = this.currentPlayer === 'black' ? 'white' : 'black';
        this.updateStatus();

        // AI回合
        if (this.isAIMode && this.currentPlayer === 'white' && !this.gameOver) {
            this.isAIThinking = true;
            this.boardElement.classList.add('thinking');
            
            // 添加随机延迟使AI走棋更自然
            await new Promise(resolve => setTimeout(resolve, 500 + Math.random() * 1000));
            
            const aiMove = this.getAIMove();
            if (aiMove) {
                this.makeMove(aiMove.row, aiMove.col);
            }
            
            this.isAIThinking = false;
            this.boardElement.classList.remove('thinking');
        }
    }

    getAIMove() {
        const moves = this.getAvailableMoves();
        if (moves.length === 0) return null;

        switch (this.aiDifficulty) {
            case 'easy':
                return this.getRandomMove(moves);
            case 'medium':
                return Math.random() < 0.7 ? this.getBestMove() : this.getRandomMove(moves);
            case 'hard':
                return this.getBestMove();
            default:
                return this.getBestMove();
        }
    }

    getAvailableMoves() {
        const moves = [];
        for (let i = 0; i < this.boardSize; i++) {
            for (let j = 0; j < this.boardSize; j++) {
                if (this.board[i][j] === null) {
                    moves.push({ row: i, col: j });
                }
            }
        }
        return moves;
    }

    getRandomMove(moves) {
        return moves[Math.floor(Math.random() * moves.length)];
    }

    getBestMove() {
        let bestScore = -Infinity;
        let bestMove = null;
        const moves = this.getAvailableMoves();

        for (const move of moves) {
            const score = this.evaluateMove(move.row, move.col);
            if (score > bestScore) {
                bestScore = score;
                bestMove = move;
            }
        }

        return bestMove;
    }

    evaluateMove(row, col) {
        let score = 0;
        const directions = [
            [-1, -1], [-1, 0], [-1, 1],
            [0, -1],           [0, 1],
            [1, -1],  [1, 0],  [1, 1]
        ];

        for (const [dx, dy] of directions) {
            score += this.evaluateDirection(row, col, dx, dy);
        }

        score += this.getPositionWeight(row, col);
        return score;
    }

    evaluateDirection(row, col, dx, dy) {
        let score = 0;
        let ownCount = 0;
        let oppCount = 0;
        let space = 0;

        // 检查正向
        for (let i = 1; i < 5; i++) {
            const newRow = row + dx * i;
            const newCol = col + dy * i;
            if (!this.isValidPosition(newRow, newCol)) break;

            const cell = this.board[newRow][newCol];
            if (cell === 'white') ownCount++;
            else if (cell === 'black') oppCount++;
            else space++;
        }

        // 检查反向
        for (let i = 1; i < 5; i++) {
            const newRow = row - dx * i;
            const newCol = col - dy * i;
            if (!this.isValidPosition(newRow, newCol)) break;

            const cell = this.board[newRow][newCol];
            if (cell === 'white') ownCount++;
            else if (cell === 'black') oppCount++;
            else space++;
        }

        // 评分规则
        if (ownCount >= 4) score += 10000;
        else if (oppCount >= 4) score += 9000;
        else if (ownCount === 3 && space >= 1) score += 1000;
        else if (oppCount === 3 && space >= 1) score += 900;
        else if (ownCount === 2 && space >= 2) score += 100;
        else if (oppCount === 2 && space >= 2) score += 90;
        else if (ownCount === 1 && space >= 3) score += 10;
        else if (oppCount === 1 && space >= 3) score += 9;

        return score;
    }

    getPositionWeight(row, col) {
        const centerWeight = 3;
        const centerRow = Math.floor(this.boardSize / 2);
        const centerCol = Math.floor(this.boardSize / 2);
        const distanceToCenter = Math.max(
            Math.abs(row - centerRow),
            Math.abs(col - centerCol)
        );
        return (this.boardSize - distanceToCenter) * centerWeight;
    }

    isValidPosition(row, col) {
        return row >= 0 && row < this.boardSize && col >= 0 && col < this.boardSize;
    }

    isValidMove(row, col) {
        return this.board[row][col] === null;
    }

    checkWin(row, col) {
        const directions = [
            [[0, 1], [0, -1]],  // 水平
            [[1, 0], [-1, 0]],  // 垂直
            [[1, 1], [-1, -1]], // 对角线
            [[1, -1], [-1, 1]]  // 反对角线
        ];

        for (let direction of directions) {
            const line = [[row, col]];
            let count = 1;

            for (let [deltaRow, deltaCol] of direction) {
                let currentRow = row + deltaRow;
                let currentCol = col + deltaCol;

                while (
                    currentRow >= 0 &&
                    currentRow < this.boardSize &&
                    currentCol >= 0 &&
                    currentCol < this.boardSize &&
                    this.board[currentRow][currentCol] === this.currentPlayer
                ) {
                    count++;
                    line.push([currentRow, currentCol]);
                    currentRow += deltaRow;
                    currentCol += deltaCol;
                }
            }

            if (count >= 5) {
                this.winningPieces = line;
                return true;
            }
        }

        return false;
    }

    highlightWinningPieces() {
        this.winningPieces.forEach(([row, col], index) => {
            const cell = document.querySelector(`[data-row="${row}"][data-col="${col}"]`);
            const piece = cell.querySelector('.piece');
            setTimeout(() => {
                piece.style.transform = 'translate(-50%, -50%) scale(1.2)';
                piece.style.boxShadow = '0 0 15px gold';
                piece.style.transition = 'all 0.3s ease';
            }, index * 100);
        });
    }

    updateStatus() {
        const status = document.getElementById('status');
        if (status && !this.gameOver) {
            const currentPlayerText = this.currentPlayer === 'black' ? '黑子' : (this.isAIMode ? 'AI' : '白子');
            status.textContent = `当前回合: ${currentPlayerText}`;
            status.style.color = this.currentPlayer === 'black' ? '#000' : '#666';
        }
    }

    updateScores() {
        const blackScore = document.getElementById('black-score');
        const whiteScore = document.getElementById('white-score');
        if (blackScore) blackScore.textContent = this.scores.black;
        if (whiteScore) whiteScore.textContent = this.scores.white;

        if (this.gameOver) {
            const scoreCard = document.querySelector(`.score-card.${this.currentPlayer}`);
            if (scoreCard) {
                scoreCard.classList.add('winner-celebrate');
                setTimeout(() => {
                    scoreCard.classList.remove('winner-celebrate');
                }, 1000);
            }
        }
    }

    showWinner() {
        const modal = document.getElementById('game-over-modal');
        const message = document.getElementById('winner-message');
        if (modal && message) {
            const winner = this.currentPlayer === 'black' ? '黑方' : (this.isAIMode ? 'AI' : '白方');
            message.textContent = `${winner}获胜！`;
            modal.classList.add('show');

            const inkSplash = document.querySelector('.ink-splash');
            if (inkSplash) {
                inkSplash.style.animation = 'none';
                inkSplash.offsetHeight;
                inkSplash.style.animation = null;
            }
        }
    }

    hideModal() {
        const modal = document.getElementById('game-over-modal');
        if (modal) {
            modal.classList.remove('show');
        }
    }

    restart() {
        this.board = Array(this.boardSize).fill().map(() => Array(this.boardSize).fill(null));
        this.currentPlayer = 'black';
        this.gameOver = false;
        this.winningPieces = [];
        this.isAIThinking = false;
        
        const cells = document.querySelectorAll('.cell');
        cells.forEach(cell => {
            while (cell.firstChild) {
                cell.removeChild(cell.firstChild);
            }
        });

        if (this.boardElement) {
            this.boardElement.classList.remove('thinking');
        }
        this.hideModal();
        this.updateStatus();
    }
}

// 确保DOM完全加载后再初始化游戏
document.addEventListener('DOMContentLoaded', () => {
    window.game = new Gomoku(); // 将游戏实例存储在全局变量中，方便调试
});